package com.xinchili.autoddl.autoClass.util;

import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

public class JdbcUtils {

    public static boolean tableExists(JdbcTemplate jdbcTemplate, String tableName) {
        String sql = "SHOW TABLES LIKE ?";
        List<String> result = jdbcTemplate.queryForList(sql, String.class, tableName);
        return !result.isEmpty();
    }

    public static Set<String> getTableColumns(JdbcTemplate jdbcTemplate, String tableName) {
        String sql = "DESCRIBE " + tableName;
        List<String> columns = jdbcTemplate.query(sql, (rs, rowNum) -> rs.getString("Field"));
        Set<String> set = new HashSet<>();
        for (String s : columns) {
            set.add(s.toLowerCase());
        }
        return set;
    }

    public static Map<String, String> getColumnTypes(JdbcTemplate jdbcTemplate, String tableName) {
        String sql = "DESCRIBE " + tableName;
        Map<String, String> map = new HashMap<>();
        jdbcTemplate.query(sql, rs -> {
            String name = rs.getString("Field");
            String type = rs.getString("Type");
            map.put(name.toUpperCase(), type.toUpperCase());
        });
        return map;
    }

    public static Map<String, String> getColumnComments(JdbcTemplate jdbcTemplate, String tableName) {
        String sql = "SELECT COLUMN_NAME, COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";
        Map<String, String> map = new HashMap<>();
        jdbcTemplate.query(sql, rs -> {
            String name = rs.getString("COLUMN_NAME");
            String comment = rs.getString("COLUMN_COMMENT");
            map.put(name.toUpperCase(), comment);
        }, tableName);
        return map;
    }
}
